<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 返回按钮 -->
    <div class="bg-white border-b">
      <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <el-button @click="goBack" :icon="ArrowLeft" class="mb-0">
          返回控制台
        </el-button>
      </div>
    </div>

    <div class="max-w-4xl mx-auto py-6 sm:px-6 lg:px-8">
      <div class="px-4 py-6 sm:px-0">
        <!-- 页面标题 -->
        <div class="mb-8">
          <h1 class="text-3xl font-bold text-gray-900">语音设置</h1>
          <p class="mt-2 text-sm text-gray-600">个性化您的语音交互体验</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 左侧：语音偏好设置 -->
          <div class="space-y-6">
            <!-- 语音参数设置 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
                <el-icon class="mr-2"><Microphone /></el-icon>
                语音参数
              </h3>
              
              <el-form
                ref="voiceFormRef"
                :model="voiceForm"
                :rules="voiceRules"
                label-width="100px"
                size="large"
              >
                <!-- 语速设置 -->
                <el-form-item label="语速" prop="voiceSpeed">
                  <div class="w-full">
                    <el-slider
                      v-model="voiceForm.voiceSpeed"
                      :min="0.5"
                      :max="2.0"
                      :step="0.1"
                      :format-tooltip="formatSpeedTooltip"
                      class="mb-2"
                    />
                    <div class="flex justify-between text-xs text-gray-500">
                      <span>0.5x</span>
                      <span>1.0x</span>
                      <span>2.0x</span>
                    </div>
                  </div>
                </el-form-item>

                <!-- 音调设置 -->
                <el-form-item label="音调" prop="voicePitch">
                  <div class="w-full">
                    <el-slider
                      v-model="voiceForm.voicePitch"
                      :min="0.5"
                      :max="2.0"
                      :step="0.1"
                      :format-tooltip="formatPitchTooltip"
                      class="mb-2"
                    />
                    <div class="flex justify-between text-xs text-gray-500">
                      <span>0.5x</span>
                      <span>1.0x</span>
                      <span>2.0x</span>
                    </div>
                  </div>
                </el-form-item>

                <!-- 音色选择 -->
                <el-form-item label="音色" prop="voiceTone">
                  <el-select v-model="voiceForm.voiceTone" placeholder="请选择音色" class="w-full">
                    <el-option label="女声" value="female" />
                    <el-option label="男声" value="male" />
                    <el-option label="童声" value="child" />
                    <el-option label="阳光" value="sunny" />
                  </el-select>
                </el-form-item>

                <!-- 语言选择 -->
                <el-form-item label="语言" prop="voiceLanguage">
                  <el-select v-model="voiceForm.voiceLanguage" placeholder="请选择语言" class="w-full">
                    <el-option label="自动检测" value="auto" />
                    <el-option label="中文" value="Chinese" />
                    <el-option label="英文" value="English" />
                    <el-option label="混合" value="Mixed" />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>

            <!-- AI设置 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
                <el-icon class="mr-2"><Monitor /></el-icon>
                AI设置
              </h3>
              
              <div class="space-y-4">
                <!-- 默认角色类型 -->
                <div class="flex items-center justify-between">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">默认角色类型</h4>
                    <p class="text-xs text-gray-500">选择您偏好的AI角色类型</p>
                  </div>
                  <el-select v-model="voiceForm.preferredCharacterType" size="small" class="w-32">
                    <el-option label="朋友" value="friend" />
                    <el-option label="心理咨询师" value="psychologist" />
                    <el-option label="老师" value="teacher" />
                    <el-option label="医生" value="doctor" />
                  </el-select>
                </div>

                <!-- 情绪检测 -->
                <div class="flex items-center justify-between">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">自动情绪检测</h4>
                    <p class="text-xs text-gray-500">AI会根据您的语音情绪调整回复</p>
                  </div>
                  <el-switch v-model="voiceForm.autoEmotionDetection" />
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：通知和隐私设置 -->
          <div class="space-y-6">
            <!-- 通知设置 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
                <el-icon class="mr-2"><Bell /></el-icon>
                通知设置
              </h3>
              
              <div class="space-y-4">
                <!-- 通知总开关 -->
                <div class="flex items-center justify-between">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">启用通知</h4>
                    <p class="text-xs text-gray-500">接收系统通知和提醒</p>
                  </div>
                  <el-switch v-model="voiceForm.notificationEnabled" />
                </div>

                <!-- 语音通知 -->
                <div class="flex items-center justify-between">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">语音通知</h4>
                    <p class="text-xs text-gray-500">播放语音通知和提醒</p>
                  </div>
                  <el-switch v-model="voiceForm.voiceNotificationEnabled" />
                </div>
              </div>
            </div>

            <!-- 隐私设置 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
                <el-icon class="mr-2"><Lock /></el-icon>
                隐私设置
              </h3>
              
              <div class="space-y-4">
                <!-- 隐私级别 -->
                <div>
                  <h4 class="text-sm font-medium text-gray-900 mb-2">隐私级别</h4>
                  <el-radio-group v-model="voiceForm.privacyLevel" class="w-full">
                    <div class="space-y-2">
                      <el-radio :label="1" class="w-full">
                        <div>
                          <div class="text-sm font-medium">标准</div>
                          <div class="text-xs text-gray-500">基本隐私保护，记录必要信息</div>
                        </div>
                      </el-radio>
                      <el-radio :label="2" class="w-full">
                        <div>
                          <div class="text-sm font-medium">高</div>
                          <div class="text-xs text-gray-500">增强隐私保护，限制数据收集</div>
                        </div>
                      </el-radio>
                      <el-radio :label="3" class="w-full">
                        <div>
                          <div class="text-sm font-medium">最高</div>
                          <div class="text-xs text-gray-500">最高隐私保护，最小化数据收集</div>
                        </div>
                      </el-radio>
                    </div>
                  </el-radio-group>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6">操作</h3>
              
              <div class="space-y-3">
                <el-button
                  type="primary"
                  :loading="loading"
                  @click="handleSave"
                  class="w-full"
                  size="large"
                >
                  保存设置
                </el-button>
                
                <el-button
                  type="default"
                  :loading="resetLoading"
                  @click="handleReset"
                  class="w-full"
                  size="large"
                >
                  重置为默认
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { 
  ArrowLeft, 
  Microphone, 
  Monitor, 
  Bell, 
  Lock 
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { 
  getVoicePreferences, 
  updateVoicePreferences, 
  resetVoicePreferences,
  type VoicePreferencesUpdateDTO
} from '@/api/user'
import type { VoicePreferences } from '@/types/chat'

// 路由和状态
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const voiceFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const resetLoading = ref(false)

// 语音设置表单
const voiceForm = reactive<VoicePreferencesUpdateDTO>({
  preferredCharacterType: 'friend',
  voiceSpeed: 1.0,
  voicePitch: 1.0,
  voiceTone: 'female',
  voiceLanguage: 'auto',
  autoEmotionDetection: true,
  privacyLevel: 1,
  notificationEnabled: true,
  voiceNotificationEnabled: true
})

// 表单验证规则
const voiceRules: FormRules = {
  voiceSpeed: [
    { required: true, message: '请设置语速', trigger: 'blur' }
  ],
  voicePitch: [
    { required: true, message: '请设置音调', trigger: 'blur' }
  ],
  voiceTone: [
    { required: true, message: '请选择音色', trigger: 'change' }
  ],
  voiceLanguage: [
    { required: true, message: '请选择语言', trigger: 'change' }
  ]
}

/**
 * 返回控制台
 */
const goBack = () => {
  router.push('/dashboard')
}

/**
 * 加载语音设置
 */
const loadVoiceSettings = async () => {
  try {
    const response = await getVoicePreferences(parseInt(authStore.userInfo?.id || '1'))
    
    // 检查响应结构 - 拦截器已经处理了响应
    let settings = null
    if (response && typeof response === 'object' && response.preferredCharacterType !== undefined) {
      // response 本身就是语音设置数据对象
      settings = response
    } else if (response.data && typeof response.data === 'object' && response.data.preferredCharacterType !== undefined) {
      // response.data 是语音设置数据对象
      settings = response.data
    } else if (response.data && response.data.code === 200 && response.data.data) {
      // 包装格式: { code: 200, message: "操作成功", data: {...} }
      settings = response.data.data
    } else {
      ElMessage.error('语音设置数据格式不正确')
      return
    }
    
    // 更新表单数据
    Object.assign(voiceForm, {
      preferredCharacterType: settings.preferredCharacterType || 'friend',
      voiceSpeed: settings.voiceSpeed || 1.0,
      voicePitch: settings.voicePitch || 1.0,
      voiceTone: settings.voiceTone || 'female',
      voiceLanguage: settings.voiceLanguage || 'auto',
      autoEmotionDetection: settings.autoEmotionDetection ?? true,
      privacyLevel: settings.privacyLevel || 1,
      notificationEnabled: settings.notificationEnabled ?? true,
      voiceNotificationEnabled: settings.voiceNotificationEnabled ?? true
    })
  } catch (error) {
    console.error('加载语音设置失败:', error)
    ElMessage.error('加载语音设置失败')
  }
}

/**
 * 保存语音设置
 */
const handleSave = async () => {
  if (!voiceFormRef.value) return

  try {
    await voiceFormRef.value.validate()
    
    loading.value = true

    await updateVoicePreferences(parseInt(authStore.userInfo?.id || '1'), voiceForm)
    ElMessage.success('语音设置保存成功')
  } catch (error) {
    console.error('Save voice settings failed:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 重置为默认设置
 */
const handleReset = async () => {
  try {
    resetLoading.value = true

    const response = await resetVoicePreferences(parseInt(authStore.userInfo?.id || '1'))
    
    // 检查响应结构 - 拦截器已经处理了响应
    let defaultSettings = null
    if (response && typeof response === 'object' && response.preferredCharacterType !== undefined) {
      // response 本身就是语音设置数据对象
      defaultSettings = response
    } else if (response.data && typeof response.data === 'object' && response.data.preferredCharacterType !== undefined) {
      // response.data 是语音设置数据对象
      defaultSettings = response.data
    } else if (response.data && response.data.code === 200 && response.data.data) {
      // 包装格式: { code: 200, message: "操作成功", data: {...} }
      defaultSettings = response.data.data
    } else {
      ElMessage.error('重置数据格式不正确')
      return
    }
    
    // 更新表单数据为默认值
    Object.assign(voiceForm, {
      preferredCharacterType: defaultSettings.preferredCharacterType || 'friend',
      voiceSpeed: defaultSettings.voiceSpeed || 1.0,
      voicePitch: defaultSettings.voicePitch || 1.0,
      voiceTone: defaultSettings.voiceTone || 'female',
      voiceLanguage: defaultSettings.voiceLanguage || 'auto',
      autoEmotionDetection: defaultSettings.autoEmotionDetection ?? true,
      privacyLevel: defaultSettings.privacyLevel || 1,
      notificationEnabled: defaultSettings.notificationEnabled ?? true,
      voiceNotificationEnabled: defaultSettings.voiceNotificationEnabled ?? true
    })
    
    ElMessage.success('已重置为默认设置')
  } catch (error) {
    console.error('重置语音设置失败:', error)
    ElMessage.error('重置失败，请重试')
  } finally {
    resetLoading.value = false
  }
}

/**
 * 格式化语速提示
 */
const formatSpeedTooltip = (value: number) => {
  return `${value}x`
}

/**
 * 格式化音调提示
 */
const formatPitchTooltip = (value: number) => {
  return `${value}x`
}

// 组件挂载时初始化数据
onMounted(() => {
  loadVoiceSettings()
})
</script>

<style scoped>
/* 自定义样式 */
.el-form-item {
  margin-bottom: 24px;
}

.el-slider {
  margin: 8px 0;
}

.el-radio {
  margin-right: 0;
  margin-bottom: 8px;
}

.el-radio__label {
  padding-left: 8px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .lg\:grid-cols-2 {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 640px) {
  .max-w-4xl {
    padding: 0 16px;
  }
  
  .bg-white {
    padding: 20px;
  }
}

/* 动画效果 */
.transition-all {
  transition: all 0.3s ease;
}

/* 滑块样式优化 */
:deep(.el-slider__runway) {
  background-color: #e5e7eb;
}

:deep(.el-slider__bar) {
  background-color: #3b82f6;
}

:deep(.el-slider__button) {
  border-color: #3b82f6;
}
</style>
